<template>
  <div class="app-container">
<!--    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="128px" style="padding-top: 15px; background: #f7f5fc; margin-bottom: 20px;">
      <el-form-item label="手机号码" prop="consumerAccountId">
        <el-input
          v-model="queryParams.consumerAccountId"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="授权状态" prop="consumerId">
        <el-input
          v-model="queryParams.consumerId"
          placeholder="请选择授权状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>-->
    <div style="display: flex;width: 100%; justify-content: flex-start;">
      <div style="width: 25%; margin-right: 20px;padding-bottom: 10px">
        <div style="padding-bottom: 5px; font-size: 14px; font-weight: bold;">
          场站设备列表
          <el-input
            placeholder="输入关键字进行过滤"
            v-model="filterText">
          </el-input>
        </div>
        <el-tree :filter-node-method="filterNode" ref="deviceRef" class="tree-border"
                 :data="deviceOptions" :props="defaultProps" @node-click="handleNodeClick"
                 icon-class="el-tree-node__expand-icon el-icon-caret-right"
                 style="padding: 10px;height: 600px; overflow: auto"></el-tree>
      </div>
      <div style="width: 74%; padding-top: 5px;">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
             @click="openAdminDia"
           >新增超级用户</el-button>
         </el-col>
         <el-col :span="1.5">
           <el-button
             type="success"
             icon="el-icon-edit"
             size="mini"
             :disabled="single"
             @click="moneyPays"
           >批量充值</el-button>
         </el-col>

         <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
       </el-row>
       <el-table v-loading="loading" :data="SpecialConsumerList" @selection-change="handleSelectionChange" highlight-current-row>
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="主键" align="center" prop="id" />
         <el-table-column label="用户账户ID" align="center" prop="consumerId" />
         <el-table-column label="用户昵称" align="center" prop="nickName" />
         <el-table-column label="手机号" align="center" prop="phoneNumber" />
         <el-table-column label="授权时间" align="center" prop="createTime" >
           <template slot-scope="scope">
             <span>{{ parseTime(scope.row.createTime) }}</span>
           </template>
         </el-table-column>
         <el-table-column label="授权状态" align="center" prop="status" >
           <template slot-scope="scope">
           <el-switch
             disabled
             v-model="scope.row.status"
             active-value="1"
             inactive-value="0"
             active-color="#13ce66"
             inactive-color="#ff4949">
           </el-switch>
           </template>
         </el-table-column>
         <el-table-column label="管理" align="center" class-name="small-padding fixed-width">
           <template slot-scope="scope">
             <el-button
               :class="['text-button', { 'active': active===scope.$index + 'handleAuth' }]"
               size="mini"
               type="text"
               icon="el-icon-setting"
               @click="handleAuth(scope.row),active=scope.$index + 'handleAuth'"
               v-hasPermi="['business:specialConsumer:edit']"
             >授权管理</el-button>
             <el-button
               :class="['text-button', { 'active': active===scope.$index + 'handleMoney' }]"
               size="mini"
               type="text"
               icon="el-icon-coin"
               @click="handleMoney(scope.row),active=scope.$index + 'handleMoney'"
               v-hasPermi="['business:specialConsumer:remove']"
             >充值管理</el-button>
           </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
           <template slot-scope="scope">
<!--             <el-button
               size="mini"
               type="text"
               icon="el-icon-edit"
               @click="handleUpdate(scope.row)"
               v-hasPermi="['business:specialConsumer:edit']"
             >详情</el-button>-->
             <el-button
               size="mini"
               type="text"
               icon="el-icon-delete"
               @click="handleDelete(scope.row)"
               v-hasPermi="['business:specialConsumer:remove']"
             >删除</el-button>
           </template>
         </el-table-column>
       </el-table>

       <pagination
         v-show="total>0"
         :total="total"
         :page.sync="queryParams.pageNum"
         :limit.sync="queryParams.pageSize"
         @pagination="getList"
       />
     </div>
   </div>
    <!-- 新增超级用户对话框 -->
    <el-dialog :title="title" :visible.sync="openAdmin" width="500px" append-to-body>
      <div style="padding-bottom: 10px; font-weight: bold; border-bottom: 1px solid #f7f5fc; margin-bottom: 10px;">查询用户手机号</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="mini" style="margin-bottom: 10px;">
          <el-input v-model="form.consumerAccountId" size="mini" placeholder="请输入用户手机号" style="width: 240px; margin-right: 20px;"/>
          <el-button type="primary" plain size="mini" @click="submitFormSearch">查询</el-button>
      </el-form>
      <el-table v-if="SpecialConsumerSearchList.length > 0" size="mini" v-loading="loadingSearch" border :data="SpecialConsumerSearchList" @selection-change="handleSelectionChange">
        <el-table-column label="用户账户ID" align="center" prop="consumerId" />
        <!--<el-table-column label="手机号码" align="center" prop="phoneNumber" />-->
        <el-table-column label="用户昵称" align="center" prop="nickName" />
      </el-table>
      <div style="padding-bottom: 10px; font-weight: bold; border-bottom: 1px solid #f7f5fc; margin-bottom: 10px; margin-top: 10px;">选择场站设备</div>
      <el-tree
        style="margin-top: 0px; padding: 10px 0;"
        class="tree-border"
        :data="deviceOptions"
        show-checkbox
        ref="device"
        node-key="id"
        :check-strictly="false"
        empty-text="加载中，请稍候"
        :props="defaultProps"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAddAdmin">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 授权管理对话框 -->
    <el-dialog :title="title" :visible.sync="openAuth" width="500px" append-to-body>
      <div style="padding-bottom: 10px; font-weight: bold; border-bottom: 1px solid #f7f5fc; margin-bottom: 10px;">用户信息</div>
      <el-table size="mini" v-loading="loadingSearch" border :data="userAuth">
        <el-table-column label="用户账户ID" align="center" prop="consumerId" />
        <!--<el-table-column label="手机号码" align="center" prop="phoneNumber" />-->
        <el-table-column label="用户昵称" align="center" prop="nickName" />
      </el-table>
      <div style="padding-bottom: 10px; font-weight: bold; border-bottom: 1px solid #f7f5fc; margin-bottom: 10px; margin-top: 10px;">选择场站设备</div>
      <el-tree
        style="margin-top: 0px; padding: 10px 0;height: 500px;overflow:auto;"
        class="tree-border"
        :data="deviceOptions"
        show-checkbox

        ref="device"
        node-key="id"
        :check-strictly="false"
        empty-text="加载中，请稍候"
        :props="defaultProps"
        accordion
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAddAuth">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 充值管理对话框 -->
    <el-dialog :title="title" :visible.sync="openMoney" width="500px" append-to-body>
      <div v-if="Object.keys(userInfo).length == 0">
        <div style="padding-bottom: 10px; font-weight: bold; margin-bottom: 10px; margin-top: 10px;">选择的用户</div>
        <el-tag v-for="(item, index) in selectedUser" :key="index" style="margin-right: 10px;">{{item}}</el-tag>
      </div>

      <el-descriptions v-if="Object.keys(userInfo).length > 0" class="margin-top" title="" :column="2" size="mini" border>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            充值用户
          </template>
          {{userInfo.nickName}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone"></i>
            账户信息
          </template>
          {{(userInfo.accountAmount / 100).toFixed(2)}}元
        </el-descriptions-item>
      </el-descriptions>
      <el-form ref="formMoney"  label-width="70px" size="mini" style="margin-top: 20px;">
        <el-form-item label="充值金额" >
          <el-input-number size="medium" v-model="money" @change="handleChangeMoney" :precision="2" :min="0" :max="9999" label="充值金额" style="width: 200px; margin-right: 10px;"></el-input-number>元
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <span  v-if="userInfo.accountAmount > 0">
          <el-popconfirm
            style="margin-right: 10px"
            confirm-button-text='确认'
            cancel-button-text='不用了'
            icon="el-icon-info"
            icon-color="red"
            @confirm="submitClearAccount(userInfo.consumerAccountId)"
            title="确认清空余额吗？"
          >
          <el-button slot="reference" type="danger" >清 空</el-button>
        </el-popconfirm>
        </span>


        <el-button type="primary" @click="submitFormMoney" v-if="ids.length == 0">确 定</el-button>
        <el-button type="primary" @click="submitFormMoneys" v-else>确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSpecialConsumer,
  getSpecialConsumer,
  delSpecialConsumer,
  addSpecialConsumer,
  updateSpecialConsumer,
  searchUser,
  balancePay,
  searchUserPhone,
  clearAccount
} from "@/api/business/specialConsumer";
import { getAllDevice } from '@/api/business/model'
import {isPhone} from '@/utils/validate'

export default {
  name: "SpecialConsumer",
  data() {
    return {
      active: null,
      filterText: '',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 场站特殊用户关联表管理表格数据
      SpecialConsumerList: [],
      SpecialConsumerSearchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        consumerAccountId: null,
        consumerId: null,
        deviceId: null,
        lastUpdateTime: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      deviceOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      openAdmin: false,
      openAuth: false,
      openMoney: false,
      userAuth: [],
      money: '',
      userInfo: {},
      loadingSearch: false,
      listSearch: [],
      selectedId: {
        stationId: '',
        deviceId: ''
      },
      selectedUser: []
    };
  },
  created() {
    //this.getList();
    this.getAll()
  },
  watch: {
    filterText(val) {
      this.$refs.deviceRef.filter(val);
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(a, b, c) {
      if (b.data.disabled) {
        this.$modal.msgError("该场站下无充电设备,无法查询");
        return false
      } else {
        if (b.parent.data.id) {
          this.selectedId = {
            stationId: b.parent.data.id,
            deviceId: a.id
          }
          this.getList(b.parent.data.id, a.id)
        }
      }
    },
    getAll() {
      getAllDevice().then(res => {
        let refArray = res.data.map((obj, key) => {
          let rObj = {}
          rObj.id = obj.id
          rObj.label = obj.stationName
          if (obj.devices.length > 0) {
            rObj.children = this.getChildren(obj.devices)
          } else {
            rObj.disabled = true
          }
          return rObj
        })
        this.deviceOptions = refArray
      })
    },
    getChildren(arr) {
      let refArray = arr.map((obj, key) => {
        let rObj = {}
        rObj.id = obj.deviceId
        rObj.label = obj.deviceName
        return rObj
      })
      return refArray
    },
    /** 查询场站特殊用户关联表管理列表 */
    getList(stationId, deviceId) {
      this.loading = true;
      listSpecialConsumer({stationId: stationId, deviceId: deviceId, phoneNumber: ''}).then(response => {
        this.SpecialConsumerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleAuth(row) {
      this.title = '授权管理'
      this.openAuth = true
      this.userAuth = [row]
    },
    handleMoney(row) {
      this.title = '充值管理'
      this.openMoney = true
      this.userInfo =  row
    },
    moneyPays() {
      this.title = '充值管理'
      this.userInfo = {}
      this.openMoney = true
    },
    submitFormMoney() {
      let consumerAccountIds = [this.userInfo.consumerAccountId]
      if(consumerAccountIds.length == 0) {
        this.$modal.msgError("用户不存在");
        return false
      }
      if(this.money == 0 | !this.money) {
        this.$modal.msgError("充值金额不能为0");
        return false
      }
      const params = {
        consumerAccountIds: consumerAccountIds,
        amount: (this.money * 100)
      }
      balancePay(params).then(res=>{
        this.$modal.msgSuccess("充值成功");
        this.openMoney = false
        this.money = 0
        this.getList(this.selectedId.stationId, this.selectedId.deviceId)
      })
    },
    async submitClearAccount(id){
      try {
        let res = await clearAccount(id)
        this.openMoney = false
        this.getList(this.selectedId.stationId, this.selectedId.deviceId)
      }catch (e) {

      }
    },
    submitFormMoneys() {
      if(this.ids.length == 0){
        this.$modal.msgError("未选择用户");
        return false
      }
      if(this.money == 0 | !this.money) {
        this.$modal.msgError("充值金额不能为0");
        return false
      }
      const params = {
        consumerAccountIds: this.ids,
        amount: (this.money * 100)
      }
      balancePay(params).then(res=>{
        this.$modal.msgSuccess("充值成功");
        this.openMoney = false
        this.money = 0
        this.getList(this.selectedId.stationId, this.selectedId.deviceId)
      })
    },
    // 新增超级管理员对话框
    openAdminDia() {
      this.title = '新增超级管理员'
      this.openAdmin = true
    },
    submitFormSearch() {
      if(!this.form.consumerAccountId) {
        this.$modal.msgError("请输入用户手机号");
        return false
      }
      if (!isPhone(this.form.consumerAccountId)){
        this.$modal.msgError("请输入正确的手机号");
        return false
      }
      searchUserPhone(this.form.consumerAccountId).then(res=>{
        this.SpecialConsumerSearchList = [res.data]
      })

      //console.log(this.form.consumerAccountId)
    },
    submitFormAddAdmin() {
      if(this.SpecialConsumerSearchList.length == 0) {
        this.$modal.msgError('请查询用户ID')
        return false
      }
      let Keys = this.getDeptAllCheckedKeys()
      if (Keys.length == 0) {
        this.$modal.msgError('请选择一个或多个设备')
        return false
      }
      const params = {
        consumerId: this.SpecialConsumerSearchList[0].consumerId,
        agentId: this.SpecialConsumerSearchList[0].agentId
      }
      let deviceIds = []
      Keys.forEach(item => {
        if (!item.hasOwnProperty('children')) {
          deviceIds.push(item.id)
        }
      })
      params.deviceIds = deviceIds
      addSpecialConsumer(params).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.openAdmin = false;
        this.getList(this.selectedId.stationId, this.selectedId.deviceId)
      });
    },
    submitFormAddAuth() {
      let Keys = this.getDeptAllCheckedKeys()
      if (Keys.length == 0) {
        this.$modal.msgError('请选择一个或多个设备')
        return false
      }
      const params = {
        consumerId: this.userAuth[0].consumerId,
        agentId: this.userAuth[0].agentId
      }
      let deviceIds = []
      Keys.forEach(item => {
        if (!item.hasOwnProperty('children')) {
          deviceIds.push(item.id)
        }
      })
      params.deviceIds = deviceIds
      updateSpecialConsumer(params).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.openAuth = false;
      });
    },
    getDeptAllCheckedKeys () {
      // 目前被选中的节点
      let checkedKeys = this.$refs.device.getCheckedNodes()
      return checkedKeys
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openAdmin = false
      this.openAuth = false
      this.openMoney = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        consumerAccountId: null,
        consumerId: null,
        createTime: null,
        deviceId: null,
        lastUpdateTime: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.consumerAccountId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.selectedUser = selection.map(item => item.nickName)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加场站特殊用户关联表管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSpecialConsumer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改场站特殊用户关联表管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSpecialConsumer(this.form).then(res => {
              this.$modal.msgSuccess("修改成功")
            })
          }
        }
      })
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSpecialConsumer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpecialConsumer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除场站特殊用户关联表管理编号为"' + ids + '"的数据项？').then(function () {
        return delSpecialConsumer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/SpecialConsumer/export', {
        ...this.queryParams
      }, `SpecialConsumer_${new Date().getTime()}.xlsx`)
    },
    handleChangeMoney() {}
  }
};
</script>

<style scoped>
  .el-tree-node__content{
    border-bottom: 1px solid #f4f4f4;
  }
</style>
